<?php

namespace App\Http\Controllers;

use App\Http\Repository\CommonRepository;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;

class LoginController
{
    public function login(Request $request) {
        //登录频繁操作设置
        $res = CommonRepository::detectClientId("login_".$request->getClientIp());
        if($res['code'] !== 0){
            return error($res['msg']);
        }
        if (!Auth()->attempt(['phone' => request('username'), 'password' => request('password'), 'status' => 1])) {
            return error("登录失败, 请确认用户是否存在, 启用");
        }
        $user = $request->user();
        if(!$user->status){
            return error("该用户已失效!!!");
        }
        $tokenResult = $user->createToken('Personal Access Token');

        return success("获取登录token", [
            'token' => $tokenResult->accessToken,
            'expires_in' => Carbon::parse($tokenResult->token->expires_at)->toDateTimeString()
        ]);
    }

    public function logout()
    {
        auth()->guard("api")->user()->token()->revoke();
        return success("退出登录");
    }
}
